package com.tanhua.server.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.CommentType;
import com.tanhua.dubbo.server.vo.IdType;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class VideoService {

    @Reference(version = "1.0.0")
    private VideoApi videoApi;
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    PicUploadService picUploadService;
    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    FdfsWebServer fdfsWebServer;


    /**
     * 业务层实现功能:查找小视频列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findAllVideo(Integer page, Integer pageSize) {
        //获取token校验后的信息封装成user对象
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        //创建结果集对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //获取所有的小视频对象
        List<Video> videos = videoApi.findAllVideos(userId, page, pageSize);
        //获取发布小视频的所有用户信息
        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video video : videos) {
            VideoVo videoVo = new VideoVo();
            videoVo.setId(video.getId().toHexString());
            videoVo.setUserId(video.getUserId());
            videoVo.setCover(video.getPicUrl());
            videoVo.setVideoUrl(video.getVideoUrl());
            //签名 TODO
            videoVo.setSignature("我就是,就是干到底!");
            videoVo.setCommentCount(0);//TODO 评论数
            videoVo.setHasFocus(videoApi.isFollowUser(userId,videoVo.getUserId())?1:0);//TODO 是否关注
            //是否点赞
            int resultLike = quanZiApi.judgeUserLikeAndLove(userId, videoVo.getId(), CommentType.LIKE) ? 1 : 0;
            videoVo.setHasLiked(resultLike);
            //点赞数
            Long resultLikeCount = quanZiApi.likeAndLoveCount(userId, videoVo.getId(), CommentType.LIKE);
            videoVo.setLikeCount(Convert.toInt(resultLikeCount));
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", videoVo.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            videoVo.setNickname(userInfo.getNickName());
            videoVo.setAvatar(userInfo.getLogo());
            videoVoList.add(videoVo);
        }
        pageResult.setItems(videoVoList);
        return pageResult;
    }


    /**
     * 业务层实现功能:发布小视频
     *
     * @param picUrl
     * @param vicUrl
     * @return
     */
    public Boolean saveVideo(MultipartFile picUrl, MultipartFile vicUrl) throws IOException {
        Video video = new Video();
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        video.setUserId(userId);
        video.setSeeType(1);
        //上传照片
        PicUploadResult pic = picUploadService.upload(picUrl);
        if (StringUtils.isEmpty(pic.getName())) {
            log.error("上传图片失败!");
            return false;
        }
        video.setPicUrl(pic.getName());
        //上传视频
        StorePath storePath = storageClient.uploadFile(vicUrl.getInputStream(), vicUrl.getSize(),
                StrUtil.subAfter(vicUrl.getOriginalFilename(), ".", true), null);
        video.setVideoUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
        String videoId = videoApi.saveVideo(video);
        return StringUtils.isNotEmpty(videoId);
    }


    /**
     * 业务层实现功能:点赞小视频
     */
    public Long likeVideo(String videoId) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        //1.点赞小视频
        if (!quanZiApi.likeAndLove(userId, videoId, CommentType.LIKE, null, IdType.VIDEO)) {
            return null;
        }
        //2.统计小视频点赞数量
        Long count = quanZiApi.likeAndLoveCount(userId, videoId, CommentType.LIKE);
        return count;
    }


    /**
     * 业务层实现功能:取消点赞小视频
     *
     * @param videoId
     * @return
     */
    public Long disLikeVideo(String videoId) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        //1.取消点赞小视频
        if (!quanZiApi.cancelLikeAndLove(userId, videoId, CommentType.LIKE, null, IdType.VIDEO)) {
            return null;
        }
        //2.统计小视频点赞数量
        Long count = quanZiApi.likeAndLoveCount(userId, videoId, CommentType.LIKE);
        return count;

    }


    /**
     * 业务层实现功能:发布评论
     *
     * @param comment
     * @return
     */
    public Boolean saveComment(String videoId, String comment) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        Boolean aBoolean = quanZiApi.saveLikeAndLoveAndComment(userId, videoId, CommentType.COMMENT, comment, IdType.VIDEO);
        return aBoolean;
    }


    /**
     * 业务层实现功能:获取小视频所有的评论
     *
     * @param videoId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult getAllComment(String videoId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);
        List<CommentVo> commentVos = new ArrayList<>();
        List<Comment> comments = quanZiApi.findAllComments(page, pageSize, videoId);
        for (Comment comment : comments) {
            CommentVo commentVo = new CommentVo();
            commentVo.setId(comment.getId().toHexString());
            commentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "HH:mm"));
            commentVo.setContent(comment.getContent());
            User user = UserThreadLocal.get();
            Long userId = user.getId();
            commentVo.setLikeCount(Convert.toInt(quanZiApi.likeAndLoveCount(userId, commentVo.getId(), CommentType.LIKE)));
            commentVo.setHasLiked(quanZiApi.judgeUserLikeAndLove(userId, commentVo.getId(), CommentType.LIKE) ? 1 : 0);
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", comment.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            commentVo.setAvatar(userInfo.getLogo());
            commentVo.setNickname(userInfo.getNickName());
            commentVos.add(commentVo);
        }
        pageResult.setItems(commentVos);
        return pageResult;

    }


    /**
     * 业务层熟悉功能:取消小视频关注
     *
     * @param userId
     * @return
     */
    public Boolean userUnFocus(Long userId) {
        User user = UserThreadLocal.get();
        Boolean result = videoApi.disFollowUser(user.getId(), userId);
        return result;
    }


    /**
     * 业务层熟悉功能:对小视频关注
     *
     * @param userId
     * @return
     */
    public Boolean userFocus(Long userId) {
        User user = UserThreadLocal.get();
        Boolean result = videoApi.followUser(user.getId(), userId);
        return result;
    }
}
